#coding=utf8
__author__ = 'alex'
import logging
from flask import g
from models import *

class BizException(BaseException):
    pass

def init_site_data():
    def do_or_fail(obj):
        try:
            g.db.add(obj)
            g.db.flush()
            g.db.commit()
            logging.info("object added")
        except:
            g.db.rollback()
            logging.info("%s already exists"%obj)

    do_or_fail(Admin("admin","1qasw2","管理员"))
    do_or_fail(Admin("alex","1qasw2","压力很大"))
    do_or_fail(Catalogs("消费资讯",0,0,0))
    do_or_fail(Catalogs("消费教育",0,0,1))
    do_or_fail(Catalogs("消费指导",0,0,2))
    do_or_fail(Catalogs("消费调解",0,0,3))
    do_or_fail(Catalogs("消费调查",0,0,4))


def manager_exists(name):
    return g.db.query(Admin.name==name).count()

def manager(name):
    return g.db.query(Admin).filter(Admin.name==name).one()

def _process_line(line):
    idx=1
    for i in xrange(5):
        if line[i]!="-":
            return i,line[idx-1:]
        idx+=1

def _process_text(text):
    data = []
    idx = 0
    for line in text.split("\n"):
        if not line:
            continue
        lv,ln = _process_line(line)
        names = ln.split("|")
        if len(names)>1:
            name, new_name = names
        else:
            name, new_name = names[0], None
        data.append(dict(
            name=name.strip(),
            new_name=new_name.strip() if new_name else None,
            fid = None,
            level = lv,
            idx = idx,
        ))
        idx+=1
    return data

def _log_steps(pool,lv,f,l):
    logging.error("%s -lv=%s -fahter=%s -last=%s"%([obj.id for obj in pool],lv,f,l))


def catalog_text():
    top_cats = g.db.query(Catalogs).filter(Catalogs.level==0).order_by(Catalogs.idx.asc())
    lines = []
    for cat in top_cats:
        lines.append(cat.name)
        txt = cat.text
        if txt:
            lines.append(txt)
    logging.error(u"%s"%lines)
    return u"\n".join(lines)


def sync_catalogs(top_id, text):
    text = text.replace(u"｜",u"|").replace(u"－",u"-")
    items = _process_text(text)
    if items[0]["level"]!=0:
        raise BizException, u"格式不正确"

    catalogs = g.db.query(Catalogs).order_by(Catalogs.idx.asc())

    named_catalogs = dict([(cat.name,cat) for cat in catalogs])
    new_catalogs = dict([(item["name"],item) for item in items])
    current_level = 0
    objpool = []
    current_father = top_id
    last_obj = None
    for item in items:
        if item["name"] not in named_catalogs:
            if current_level==item["level"]:
                node = Catalogs(item["name"], current_father, item["level"], item["idx"])
                g.db.add(node)
                g.db.flush()

            if current_level<item["level"]:
                node = Catalogs(item["name"], last_obj.id, item["level"], item["idx"])
                g.db.add(node)
                g.db.flush()
                objpool.append(last_obj)
                current_father = last_obj.id

            if current_level>item["level"]:
                sub = current_level-item["level"]
                for i in range(sub):
                    current_father = objpool.pop().forward_id

                node = Catalogs(item["name"], current_father, item["level"], item["idx"])
                g.db.add(node)
                g.db.flush()
            last_obj = node
            current_level=item["level"]
        else:
            node = named_catalogs[item["name"]]
            node.idx = item["idx"]
            if item["new_name"]:
                node.name = item["new_name"]
            if current_level<item["level"]:
                objpool.append(last_obj)
                current_father = last_obj.id
                if node.level != item["level"]:

                    node.forward_id = last_obj.id
            if current_level>item["level"]:
                sub = current_level-item["level"]
                for i in range(sub):
                    current_father = objpool.pop().forward_id

                if node.level != item["level"]:
                    node.forward_id = current_father
            node.level = item["level"]
            last_obj = node
            current_level=item["level"]
            g.db.flush()
        _log_steps(objpool,current_level,current_father,last_obj.id)
    for name, value in named_catalogs.iteritems():
        if name not in new_catalogs:
            g.db.delete(value)
            g.db.flush()
    g.db.commit()

def top_level():
    return g.db.query(Catalogs).filter(Catalogs.level==0).order_by(Catalogs.idx.asc())

def _strip_end(txt):
    txt = txt.strip()
    if txt[-1:]=="\r":
        return txt[:-1]
    return txt

def _splite_content(content):
    lines = content.split("\n")
    pool = []
    datas = []
    for line in lines:
        line = _strip_end(line)
        if set(list(line))!=set(["-",]):
            pool.append(line)
        else:
            datas.append("\n".join(pool))
            del pool[:]
    if pool:
        datas.append("\n".join(pool))
    return datas

def _process_type(content):
    if content.startswith("http"):
        return 0
    line=content.strip().split("\n")[0]
    if line[-3:].lower() in ['jpg','gif','png','bmp']:
        return 1
    else:
        return 2


def _process_attachment(data):
    lines=data.split("\n")
    title = lines[0]
    content = "\n".join(lines[1:])
    thetype = _process_type(content)
    return title, thetype, content


def process_content(content):
    datas = _splite_content(content)
    attachments = datas[1:]
    txt_content = datas[0]
    atts = []
    for att in attachments:
        atts.append(_process_attachment(att))
    return txt_content, atts


def post_document(catalog_id, title, content, poster):
    tx_content, attrs = process_content(content)
    document = Document(title, tx_content, catalog_id, poster)
    g.db.add(document)
    g.db.flush()
    for attr in attrs:
        document.append_attachment(*attr)
    g.db.flush()
    g.db.commit()


def txt_document(document_id):
    document = g.db.query(Document).get(document_id)
    attachments = g.db.query(Attachment).filter(Attachment.document_id==document_id).order_by(Attachment.id.asc())
    slice = []
    slice.append(document.content)
    slice.append("-------------------")
    for attachment in attachments:
        slice.append(attachment.name)
        slice.append(str(attachment))
    return "\r\n".join(slice)


def update_document(document, title, content, catalog_id):
    document.title = title
    document.catalog_id = catalog_id
    tx_content, attrs = process_content(content)
    document.content = tx_content
    g.db.query(Attachment).filter(Attachment.document_id==document.id).delete()
    for attr in attrs:
        document.append_attachment(*attr)
    g.db.flush()
    g.db.commit()










